package edu.usc.cmb.iregulome.util;

import java.util.LinkedList;
import java.util.List;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomNodeList;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;

import edu.usc.cmb.iregulome.client.eUtilsServiceClient;
import edu.usc.cmb.iregulome.client.eUtilsServiceSoap;
import gov.nih.nlm.ncbi.soap.eutils.esearch.ESearchRequest;
import gov.nih.nlm.ncbi.soap.eutils.esearch.ESearchResult;

public class NCBIContentUtil {

	private static final WebClient client = new WebClient(
			BrowserVersion.FIREFOX_3);

	public static List<String> extractSampleIdsFromSampleList() {

		List<String> sampleIds = new LinkedList<String>();
		try {
			HtmlPage p = client
					.getPage("http://www.ncbi.nlm.nih.gov/Traces/sra/sra.cgi?cmd=table&f=sample&m=data&s=sample");
			DomNodeList<HtmlElement> eList = p.getElementsByTagName("table");
			HtmlTable t = (HtmlTable) eList.get(0);

			for (HtmlTableRow row : t.getRows()) {
				String theSRSId = row.getCells().get(1).getTextContent().trim();
				if (theSRSId.equals("") || theSRSId.equals("Accession")) {
					continue;
				}
				sampleIds.add(theSRSId);
			}
		} catch (Exception e) {
			// TODO log the error
		}

		return sampleIds;
	}

	public static List<String> extractMainIdsFromWebService(String db,
			String keyword, String max) {

		List<String> mainIds = new LinkedList<String>();

		eUtilsServiceClient eService = new eUtilsServiceClient();
		eUtilsServiceSoap soap = eService.geteUtilsServiceSoap();
		ESearchRequest esq = new ESearchRequest();
		esq.setDb(db);
		esq.setTerm(keyword);
		esq.setRetMax(max);
		ESearchResult esresult = soap.run_eSearch(esq);

		for (String idString : esresult.getIdList().getId()) {
			mainIds.add(idString);
		}
		return mainIds;
	}

}
